<template>
  <div class="app-container">
    <div class="app-title">
      <span>内部机构维护</span>
    </div>
    <div class="filter-container">
      <el-row>
        <el-col :span="1">
          <i :class="[treeShows ? 'el-icon-s-fold treeI': 'el-icon-s-unfold treeI']" @click="toggerTrees" />
        </el-col>

        <el-col
          style="text-align: left; padding-left: 0px;"
          :span="2"
        >
          <i
            :class="[treeShow ? 'el-icon-s-fold treeI': 'el-icon-s-unfold treeI']"
            @click="toggerTree"
          />

        </el-col>
        <el-col
          style="text-align: right;margin-top:-20px"
          :span="20"
        >
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            @click="tosave"
          >
            新增
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            @click="handleEdit"
          >
            修改
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div
      ref="box"
      class="box"
    >
      <!-- -->
      <div
        class="left"
        :class="[isActives ? 'wid':'widss']"
      >
        <div
          :class="[treeShows ? 'treeShow' : 'treeNotShow']"

          :style="{'height' : treeHeight + 'px'}"
        >
          <AgencyTree
            class="agencyTree"
            @handleTreeQuery="handleTreeQuery"
            @getFirstAuthAgencyData="getFirstAuthAgencyData"
          />
        </div>
      </div>
      <div
        v-show="Shows"
        class="resize"
        title="收缩侧边栏"
      />
      <!-- -->
      <div
        class="left"
        :class="[isActive ? 'wid':'widss']"
      >
        <div :class="[treeShow ? 'treeShow' : 'treeNotShow']">
          <div style="height:40px; background-color:#ebecf1">
            <div style="width:100px;padding-top:10px;padding-left:20px">组织机构</div>
          </div>
          <el-input
            v-model="treeQuery"
            suffix-icon="el-icon-search"
            size="small"
            class="treeInput"
          />
          <el-tree
            ref="selectTree"
            :data="listTree"
            :props="defaultProps"
            :node-key="defaultProps.id"
            :filter-node-method="filterNode"
            :default-expanded-keys="['0']"
            @node-click="handleClick"
          />
        </div>
      </div>
      <div
        v-show="Show"
        class="resize"
        title="收缩侧边栏"
      />
      <div
        class="mid"
        :class="[ treeShows && (isActives ? 'mids': 'minc') , treeShow && (isActive ? 'mids': 'minc') ,treeShows && treeShow && 'minss' ]"
      >
        <div :class="[treeShow ? 'hasTree': 'notTree']">
          <el-table
            ref="singalTable"
            v-loading="listLoading"
            :data="list"
            :stripe="true"
            fit
            :height="tableHeight"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <template slot="empty">
              <tableEmpty />
            </template>
            <el-table-column
              type="selection"
              width="55"
              align="center"
            />
            <el-table-column
              label="序号"
              type="index"
              align="center"
              width="50"
            />
            <el-table-column
              prop="deptCode"
              label="科室编号"
              align="center"
              width="300"
            />
            <el-table-column
              prop="deptName"
              label="科室名称"
              align="center"
              width="300"
            />
            <el-table-column
              prop="deptAbbreviation"
              label="备注"
              align="center"
            />
          </el-table>

          <!--分页 -->
          <pagination
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getList"
          />
        </div>
      </div>

    </div>
    <Drag ref="icon" />

    <!-- 编辑页面部分 -->
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="dialogStatus"
      :visible.sync="dialogFormVisible"
      width="35%"
    >
      <el-form
        ref="dataForm"
        class="dialog-backgroundcolor"
        :rules="dataFormRules"
        :model="formData"
        label-position="left"
        label-width="100px"
        :disabled="formDsiabled"
      >
        <div style="margin-left: 4%">
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属科室：" />
              <el-select
                ref="selectReport"
                v-model="formData.parentName"
                placeholder="请选择"
                :clearable="clearable"
                @clear="clearHandle"
              >
                <el-option
                  :value="formData.parentId"
                  :label="formData.parentName"
                  style="width: 300px;height:200px;overflow: auto;background-color:#fff"
                >
                  <el-tree
                    ref="selectTree"
                    :data="listTree"
                    :accordion="accordion"
                    :props="defaultProps"
                    :node-key="defaultProps.id"
                    :default-expanded-keys="defaultExpandedKey"
                    @node-click="handleNodeClick"
                  />
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="科室名称："
                prop="deptName"
              />
              <el-input v-model="formData.deptName" maxlength="100" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="备注："
                prop="deptAbbreviation"
              />
              <el-input
                v-model="formData.deptAbbreviation"
                maxlength="40"
              />
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col
            v-if="operate === 'edit'"
            :span="16"
            style="text-align: right; margin-top:20px;"
          >
            <el-button
              type="primary"
              :loading="saveLoading"
              @click="updateData()"
            >
              保存
            </el-button>
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 引入方法（增删改查）
import {
  getDepartmentInfoList,
  updateDepartmentInf,
  saveDepartmentInf,
  getDepartmentTree
} from '@/api/unitInformationMaintenance/internalOrganizationMaintenance'
// 引入分页插件
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Drag from '@/components/Drag'
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
export default {
  name: 'UnitInformationMaintenance',
  // 分页组件
  components: { Pagination, Drag, tableEmpty, AgencyTree },
  data() {
    return {
      tableHeight: null,
      treeQuery: '',
      isActive: true,
      Show: false,
      treeHeight: null,
      isActives: true,
      Shows: false,
      clearable: true,
      accordion: false,
      treeShow: false,
      treeShows: false,
      saveLoading: false,
      that: this,
      list: null,
      listTree: null,
      listOptions: null,
      mineStatus: '',
      defaultExpandedKey: [],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 200,
        title: undefined,
        type: undefined,
        agencyId: ' ',
        departmentId: '0'
      },
      formData: {
        id: '',
        createTime: '',
        updateTime: '',
        agencyId: '',
        parentName: '',
        parentId: '',
        levelNo: '',
        isLeaf: '',
        deptCode: '',
        deptAbbreviation: '',
        deptType: '',
        deptState: '',
        isDeleted: ''
      },
      // 清空 formData
      restetFormData() {
        this.formData = {
          id: '',
          createTime: '',
          updateTime: '',
          agencyId: '',
          agencyName: '',
          deptName: '',
          parentId: '',
          parentName: '',
          levelNo: '',
          isLeaf: '',
          deptCode: '',
          deptAbbreviation: '',
          deptType: '',
          deptState: '',
          isDeleted: ''
        }
      },
      formDsiabled: false,
      operate: 'edit',
      dialogFormVisible: false,
      dialogStatus: '',
      dataFormRules: {
        deptName: [
          { required: true, message: '请输入科室名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    treeQuery(val) {
      this.$refs.selectTree.filter(val)
    },
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  mounted() {
    this.dragController()
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  created() {
    this.getList()
    this.getTree()
    this.getTrees()
  },
  methods: {
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 218
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
      this.treeHeight = this.tableHeight
    },
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
        // 树返回默认单位信息查询
    getFirstAuthAgencyData(data) {
      this.listQuery.agencyId = data.id
      this.getList()
    },
    // 获取所有数据
    getList() {
      this.listLoading = true
      getDepartmentInfoList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 修改弹框
    handleEdit() {
      this.formDsiabled = false
      this.operate = 'edit'
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }

      this.dialogStatus = '修改科室'
      this.dialogFormVisible = true
      this.formData = Object.assign({}, selection[0])
      this.formData.parentName = this.$refs.selectTree.getNode(
        this.formData.parentId
      ).data[this.defaultProps.label] // 初始化显示
      this.$refs.selectTree.setCurrentKey(this.formData.parentId)
      if (this.formData.parentName === '组织机构') {
        this.clearHandle()
      }

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存弹框
    tosave() {
      this.restetFormData()
      this.formDsiabled = false
      this.operate = 'edit'
      this.dialogStatus = '新增科室'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存、修改方法

    updateData() {
      if (this.formData.id === '') {
        // 新增
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            this.saveLoading = true
            this.formData.agencyId = this.listQuery.agencyId
            const tempData = Object.assign({}, this.formData)
            saveDepartmentInf(tempData).then(response => {
              if (response.data === '500') {
                this.$message({
                  showClose: true,
                  message: '科室名称已存在，不允许保存',
                  type: 'warning',
                  duration: 4000
                })
                this.saveLoading = false
              } else if (response.data === '200') {
                this.dialogFormVisible = false
                this.$message({
                  showClose: true,
                  message: '保存成功',
                  type: 'success',
                  duration: 4000
                })
                this.saveLoading = false
              }
              this.handleFilter()
            })
          }
        })
      } else {
        // 修改
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            const tempData = Object.assign({}, this.formData)
            updateDepartmentInf(tempData).then(response => {
              if (response.data === '500') {
                this.$message({
                  showClose: true,
                  message: '科室名称已存在，不允许保存',
                  type: 'warning',
                  duration: 4000
                })
              } else if (response.data === '200') {
                this.dialogFormVisible = false
                this.$message({
                  showClose: true,
                  message: '修改成功',
                  type: 'success',
                  duration: 4000
                })
              }

              this.handleFilter()
            })
          }
        })
      }
    },
    // 刷新
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
      this.getTree()
      this.getTrees()
    },
    // 切换树是否显示
    toggerTrees() {
      this.treeShows = !this.treeShows
      this.isActives = !this.isActives
      this.Shows = !this.Shows
    },
    // 树方法
    handleTreeQuery(data) {
      this.treeData = data
      this.handleTree(data)
    },
    handleTree(data) {
      this.listQuery.agencyId = data.id
      this.getList()
      this.getTree() // ......
    },
    // 树查询过滤
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 切换树是否显示
    toggerTree() {
      this.isActive = !this.isActive
      this.Show = !this.Show
      this.treeShow = !this.treeShow
    },
    // 获取数内容
    getTree() {
      getDepartmentTree(this.listQuery).then(response => {
        this.listTree = response.data
      })
    },
    getTrees() {
      getDepartmentTree(this.listQuery).then(response => {
        this.listTree = response.data
      })
    },
    handleNodeClick(data) {
      this.formData.parentId = data.id
      this.formData.parentName = data.label
      if (this.formData.parentName === '组织机构') {
        this.clearHandle()
      } else {
        this.$refs.selectReport.blur()
      }
    },
    handleClick(data) {
      this.listQuery.departmentId = data.id
      this.getList()
    },
    // 清除下拉树选中
    clearHandle() {
      this.formData.parentName = ''
      this.formData.parentId = null
      this.defaultExpandedKey = []
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/border.scss"; /*引入公共样式*/
.treeInput {
  width: 100% !important;
  height: 40px !important;

  .el-input__inner {
    height: 35px;
  }
}
  .editFormDeviation {
    margin-left: 10%;
  }
  .viewFormDeviation {
    margin-left: 6%;
  }
    .formDeviation {
    margin-left: 5%;
  }
  ::v-deep .el-select {
    .el-input {
      height: auto !important;
    }
  }
</style>
